use std::{
    fs::File,
    io::{Read, Write},
    os::windows::io::{FromRawHandle, RawHandle},
    ptr,
    thread,
};

use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;

#[link(name = "kernel32")]
unsafe extern "system" {
    fn CreatePipe(
        hReadPipe: *mut HANDLE,
        hWritePipe: *mut HANDLE,
        lpPipeAttributes: *mut SECURITY_ATTRIBUTES,
        nSize: u32,
    ) -> i32;
}
// 管道工作实例 可以工作
fn main() {
    unsafe {
        // 1. 创建匿名管道
        let mut read_pipe: HANDLE = std::ptr::null_mut();
        let mut write_pipe: HANDLE = std::ptr::null_mut();

        let mut sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: ptr::null_mut(),
            bInheritHandle: 1,
        };

        if CreatePipe(&mut read_pipe, &mut write_pipe, &mut sa, 0) == 0 {
            panic!("❌ CreatePipe 创建失败");
        }

        println!("✅ Pipe 创建成功");

        // ✅ 直接将 write_pipe 包装为 File，并传入线程
        let write_file = File::from_raw_handle(write_pipe as RawHandle);

        let writer = thread::spawn(move || {
            let mut file = write_file;
            let msg = b"Hello from writer thread!\n";
            file.write_all(msg).unwrap();
            println!("✍️ 写入线程完成");
        });

        // 主线程读
        // Rust 的 std::fs::File 本身是 Send，你只要把 HANDLE 用 File::from_raw_handle 包起来，直接传 File 进线程就行，完全不会报错。
        let mut reader = File::from_raw_handle(read_pipe as RawHandle);
        let mut buffer = [0u8; 1024];
        let n = reader.read(&mut buffer).expect("读取失败");

        println!("📥 主线程读取到 {} 字节：", n);
        println!("{}", String::from_utf8_lossy(&buffer[..n]));

        writer.join().unwrap();

        println!("✅ Pipe 通信测试完成");
    }
}
